package archer.framework.security.utils;

import archer.framework.security.analog.AnalogContextHolder;
import archer.framework.security.analog.AnalogLoginProcessor;
import archer.framework.security.analog.AnalogUser;
import archer.framework.security.token.Subject;
import archer.framework.security.token.Token;

/**
 * 虚拟登录
 *
 * @author kent
 * @date 16/7/7.
 */
public class AnalogUtils {

    /**
     * 虚拟登录处理
     *
     * @param user
     * @param processor
     */
    public static void process(AnalogUser user, AnalogLoginProcessor processor) {

        try {
            login(user);
            processor.process();
        } finally {
            logout();
        }
    }

    private static Token login(Subject subject) {

        Token token = SubjectUtils.bindAssociatedToken(subject);
        AnalogContextHolder.set(token);
        return token;
    }

    private static void logout() {

        SubjectUtils.invalidateAssociatedToken(AnalogContextHolder.get().getId());
        AnalogContextHolder.reset();
    }
}
